package com.punch.db.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.punch.common.utils.IdGenerator;
import com.punch.db.properties.MybatisPlusAutoFillProperties;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * 自定义填充公共字段
 *
 * @author zlt
 * @date 2018/12/11
 * <p>
 * Blog: https://zlt2000.gitee.io
 * Github: https://github.com/zlt2000
 */
public class DateMetaObjectHandler implements MetaObjectHandler {
    private MybatisPlusAutoFillProperties autoFillProperties;

    public DateMetaObjectHandler(MybatisPlusAutoFillProperties autoFillProperties) {
        this.autoFillProperties = autoFillProperties;
    }

    /**
     * 是否开启了插入填充
     */
    @Override
    public boolean openInsertFill() {
        return autoFillProperties.getEnableInsertFill();
    }

    /**
     * 是否开启了更新填充
     */
    @Override
    public boolean openUpdateFill() {
        return autoFillProperties.getEnableUpdateFill();
    }

    /**
     * 插入填充，字段为空自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = getFieldValByName(autoFillProperties.getCreateTimeField(), metaObject);
        Object updateTime = getFieldValByName(autoFillProperties.getUpdateTimeField(), metaObject);
        LocalDateTime date = LocalDateTime.now();
        if (createTime == null) {
            setFieldValByName(autoFillProperties.getCreateTimeField(), date, metaObject);
        }
        if (updateTime == null) {
            setFieldValByName(autoFillProperties.getUpdateTimeField(), date, metaObject);
        }
        if (autoFillProperties.getId() == null) {
            setFieldValByName(autoFillProperties.getId(), IdGenerator.getId(), metaObject);
        }
    }

    /**
     * 更新填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime date = LocalDateTime.now();
        setFieldValByName(autoFillProperties.getUpdateTimeField(), date, metaObject);
    }
}
